//
//  PhotoBrowserViewVC.swift
//  波波微博
//
//  Created by wave on 15/8/9.
//  Copyright © 2015年 wave. All rights reserved.
//

import UIKit
import SVProgressHUD

//可重用cell
private let BBBPhotoBrowserCell = "BBBPhotoBrowserCell"



class PhotoBrowserViewVC: UIViewController {

    //URL数组
    var urls:[NSURL]
    //用户当前点击的索引值
    var selectedIndex: Int
    
    var mark = false
    
    //MARK: - 构造函数
    init(urls:[NSURL],selectedIndex:Int){

        self.urls = urls
        self.selectedIndex = selectedIndex
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func loadView() {
        
        var screenBound = UIScreen.mainScreen().bounds
        screenBound.size.width += 20
        view = UIView(frame: screenBound)
        
        setupUI()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        if mark == true {
            return
        }
        let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        
        mark = true

    }
    
    //MARK: - 监听方法
    @objc private func saveBtn(){
        
        //获取照片
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoBrowserCell
        
        //判断图像视图中是否存在图像,因为SDWebImage不一定能够下载到图像
        guard let image = cell.imageView.image else{
            
            return
        }
        
        //保存
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    //OC方法变为Swift方法
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo: AnyObject ){
        print(error)
        print(image)
        
        let msg = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(msg)
    }
    
    @objc private func closeBtn(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }

    //MARK: - 搭建界面
    private func setupUI(){
    
        //添加控件
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        //自动布局
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        let dict = ["cv":collectionView,"save":saveButton,"close":closeButton]

        //collectionView全屏
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        collectionView.frame = view.bounds
        //保存和关闭按钮
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[save(32)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[close(32)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        //设置约束关系
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[close(100)]-(>=0)-[save(100)]-28-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))

        //添加监听方法
        saveButton.addTarget(self, action: "saveBtn", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "closeBtn", forControlEvents: UIControlEvents.TouchUpInside)
        
        //设置独立控件属性
        prepareCollectionView()
    }
    
    //准备独立控件属性
    private func prepareCollectionView(){
    
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: BBBPhotoBrowserCell)
        collectionView.dataSource = self
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = view.bounds.size
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView.pagingEnabled = true
    }
    
    
    //MARK: - 懒加载
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var saveButton: UIButton = UIButton(title: "保存", color: UIColor.darkGrayColor(), fontSize: 14)
    private lazy var closeButton: UIButton = UIButton(title: "关闭", color: UIColor.darkGrayColor(), fontSize: 14)
}


extension PhotoBrowserViewVC:UICollectionViewDataSource{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(BBBPhotoBrowserCell, forIndexPath: indexPath) as! PhotoBrowserCell

        cell.imageURL = urls[indexPath.item]
        
//        cell.backgroundColor = (indexPath.item % 2 == 0) ? UIColor.redColor() : UIColor.greenColor()

        return cell
    }
    

}





